import { Component, OnInit } from '@angular/core';
import { CommonService } from '../../../../services/common.service';
import { NzMessageService } from 'ng-zorro-antd/message';

@Component({
  selector: 'app-contractextractionretrieval',
  templateUrl: './contractextractionretrieval.component.html',
  styleUrls: ['./contractextractionretrieval.component.css']
})
export class ContractextractionretrievalComponent implements OnInit {
  // 标题级数选择器
  provinceData: any = [
    {
      value: 1,
      label: 1
    },
    {
      value: 2,
      label: 2
    },
    {
      value: 3,
      label: 3
    },
    {
      value: 4,
      label: 4
    },
    {
      value: 5,
      label: 5
    },
  ];
  // 操作
  operation: '';
  // 类型
  type: '';
  // selectedProvince = '文本匹配';
  // selectedCity = '单模式匹配';
  provinceDatas: any = [
    {
      op: "文本匹配",
      type: "search"
    }, {
      op: "文本切割",
      type: "split"
    }, {
      op: "关键词检测",
      type: "filter"
    }
  ];
  cityData: any = {
    search: [{
      op: "单模式匹配",
      type: "first-search"
    }, {
      op: "多模式匹配",
      type: "multi-search"
    }, {
      op: "移除前后缀",
      type: "remove-fix"
    }],
    split: [
      {
        op: "按段落切割",
        type: "paragraph"
      }, {
        op: "按句子切割",
        type: "sentence"
      }, {
        op: "按标点切割",
        type: "punctuation"
      }, {
        op: "按词汇切割",
        type: "word"
      }
    ],
    filter: [
      {
        op: "按关键词保留",
        type: "keep"
      }, {
        op: "按关键词删除",
        type: "remove"
      }
    ]
  };
  // 标题级数
  titleLevel: any = '';
  // 标签等级挖掘开启与关闭
  switchValue = true;
  // 移除目录
  category = true;
  // 移除页眉/页脚
  headerFooter = true;
  // 对标题中的冒号进行切割
  splitColon = true;
  // 文档抽取标签列表
  AnalysisTagList: any = [
  ];
  // 搜索标签的列表
  seekTagList:any=null
  // 拿到的文档抽取标签列表的数据
  // 名称
  TagName: '';
  // id
  TagId: '';
  // 添加模型工作流模态框
  Modalwork = false;
  // 模型工作流模态框数据
  public listOfData: any = [];
  // 添加规则工作流列表
  public workflowList: any = [];
  // 删除工作流的模态框
  deleteWorkflowShow = false;
  // 点击删除拿到的当前工作流id
  deleteWorkflowId: any = '';
  // 抽取配置测试模态框
  Modaltest = false;
  // 文档结构解析测试模态框
  Modalstructu = false;
  // 测试工作流模态框
  ModalWorkflow = false;
  // 挖掘标题等级的正则表达式
  titleTemplates: any = [
    {
      value: ""
    },
    {
      value: ""
    },
  ];
  // 保存接口 挖掘标题请求体
  titleData: any = []
  // 判断保存请求体是否为空
  islength: boolean = false
  // 选择测试文件模态框
  selectModel: boolean = false;
  //申购起点测试文件
  selectConfigModel: boolean = false;
  selectWorkflowModel: boolean = false;

  allChecked = false;
  indeterminate = true;
  // 选择测试文件 多选数据
  checkOptionsOne: any = [];
  // 搜索测试文件的value
  seekFileValueOne:any=null
  // 搜索测试文件的list
  checkOptionsOneList:any=null
  checkOptionsTwo: any = [];
  // 搜索测试文件的value
  seekFileValueTwo:any=null
  // 搜索测试文件的list
  checkOptionsTwoList:any=null

  checkOptionsThree: any = [];
  // 搜索测试文件的value
  seekFileValueThree:any=null
  // 搜索测试文件的list
  checkOptionsThreeList:any=null
  // 选择器选中的文件name
  selectorName: any[] = [];
  selectorConfigName: any[] = [];
  selectorWorkflowName: any[] = [];
  // 选择器选中的文件ID
  selectorId: any = [];
  selectorConfigId: any = [];
  selectorWorkflowId: any = [];
  //标题检索模块 规则操作状态
  activeStatus = true
  // 默认全选按钮 没有被选中
  master: boolean = false;
  configMaster: boolean = false;
  workflowMaster: boolean = false;
  ModelworkflowMaster: boolean = false;
  // label 点亮
  selectLabel: any = 0
  // 剩余选择次数
  selectorLength: number = 100;
  // 测试 jobid
  JobTestId: '';
  // job 返回的数据
  Jobcontent: any = []
  conifgJobcontent: any = []

  TitleConfig: any = [
    // { is_reverse: true },
    // { search_patterns: ["产品的名称"] }
  ]
  WorkflowId: "fc11391e-a959-11eb-9e85-e1f6c457687e"
  // 搜索标签value
  seekTagValue:any=null
  // 新建标签弹窗
  addTagModelShow = false;
  // 新建标签value
  addTagValue: string = '';
  // 编辑标签弹窗
  editTagModelShow = false;
  // 编辑标签value
  editTagValue: string = "";
  // 编辑标签的id
  editLabelId: ''
  // 删除标签的弹窗
  deleteTagShow = false;
  // 新建title的list
  // 新增标签数量
  TitleList: any = [];
  // 关键词input显示
  keyword = false;
  // 删除工作流的index
  deleteIndex: any = null;
  // 工作流选择器 默认禁用
  // isAble: boolean = false;
  // 删除op工作流的model
  deleteWorkOpShow = false;
  // 删除op工作流的id
  deleteWorkOpId: any = null;
  // 删除op工作流需要的workList的下标
  workOpIndex: any = null;
  // 删除op工作流需要的workList下面的ops数组的下标
  workOpSindex: any = null;
  //Job轮询定时器
  jobTimer: any = null
  configJobTimer: any = null
  workflowJobTimer: any = null
  //
  exportFileBase64: string = "";
  exportFileName: string = "";
  // 判断当前标题等级是空还是有值 以便在接口里做数据解析
  saveisTitle: boolean = false;

  //
  testWorkFlowIds: any[] = [];
  // 测试的labelid
  testLabelId: string = "";

  //工作流测试workflowId
  singleWorkflowId: string = "";

  // 添加模型工作流里的 选择器
  ModelName: any = null
  // 添加模型tab表格选择器 防止全部选择
  radioValue = '';
  // 添加模型tab表格选择器 拿到的数据
  selectModelData: any = null
  // 模型工作流list
  ModelDataList: any = []
  // 模型工作流的index
  deleteModelIndex: any = null
  // 模型工作流的id
  deleteModelId: any = null
  // 模型工作的模态框
  deleteModelWorkShow: boolean = false
  // 测试模型工作流的模态框
  ModalWorkflowShow: boolean = false
  // 模型工作流的多选
  checkOptionsFour: any = []
  // 搜索测试文件的value
  seekFileValueFour:any=null
  // 搜索测试文件的list
  checkOptionsFourList:any=null
  // 模型多选框显示隐藏
  selectModelWorkflowModel: boolean = false
  // 新建标签ID
  addLabelId:any=null
  // 默认获取第一个 请求体id
  OneLabelId:any=null
  // 测试结果全部文本Model
  ShowDataValue:boolean = false
  // 拿到的测试name
  ShowDataName:any=null
  // 拿到的测试结果
  ShowDataExtract:any=null
  constructor(public http: CommonService,
    private message: NzMessageService) { }

  ngOnInit(): void {
    // 查询文档结构解析配置
    this.getAnalysis();
    // 查询文档抽取标签列表
    this.getAnalysisTag();


  }

  ngOnDestroy(): void {
    //Called once, before the instance is destroyed.
    //Add 'implements OnDestroy' to the class.
    if (this.jobTimer != null) {
      clearInterval(this.jobTimer);
    }
    if (this.configJobTimer != null) {
      clearInterval(this.configJobTimer);
    }
    if (this.workflowJobTimer != null) {
      clearInterval(this.workflowJobTimer);
    }
  }
  // 查询文档结构解析配置
  getAnalysis() {
    // 项目id
    let id = sessionStorage.getItem('id');
    this.http.post('/contract-extraction/extraction-mgr/query-doc-config', {
      project_id: id
    }).then((res: any) => {
      console.log(res)
      // 标题级数
      if (res && res.result && res.result.title_depth === '') {
        this.titleLevel = 2
      } else {
        this.titleLevel = res.result.title_depth
      }
      // 移除目录
      this.category = res.result.is_remove_category
      //移除页眉页脚
      this.headerFooter = res.result.is_remove_header_footer
      //使用冒号对标题进行切割，默认为true
      this.splitColon = res.result.title_split_by_colon
      // 判断后台是否返回了标题 如果返回 就显示 不返回 则不显示
      if (res.result.title_templates == '') {
        // 与标题等级联动
        switch (res.result.title_depth) {
          case 1:
            this.titleTemplates.length = 0
            this.titleTemplates.push({ value: "" });

            break;
          case 2:
            this.titleTemplates.length = 0
            this.titleTemplates.push({ value: "" }, { value: "" });

            break;
          case 3:
            this.titleTemplates.length = 0
            this.titleTemplates.push({ value: "" }, { value: "" }, { value: "" });

            break;
          case 4:
            this.titleTemplates.length = 0
            this.titleTemplates.push({ value: "" }, { value: "" }, { value: "" }, { value: "" });

            break;
          case 5:
            this.titleTemplates.length = 0
            this.titleTemplates.push({ value: "" }, { value: "" }, { value: "" }, { value: "" }, { value: "" });

            break;
        }
        // 将标题自动挖掘开启
        this.switchValue = true
      } else {
        // 将标题等级自动挖掘关闭 
        this.switchValue = false
        //挖掘标题等级的正则表达式，没有这个字段表示标题等级自动挖掘
        let titleAll = [];
        res.result.title_templates.forEach(i => {
          titleAll.push({ value: i })
        });
        this.titleTemplates = titleAll
      }
    }).catch((err: any) => {
      this.message.error(err.error_msg);
    })
  }
  // 选择器选中的
  province(e) {
    console.log(e)
    // 拿到的标题级数
    this.titleLevel = e;
    // console.log(e.value)
    switch (e) {
      case 1:
        this.titleTemplates.length = 0
        this.titleTemplates.push({ value: "" });

        break;
      case 2:
        this.titleTemplates.length = 0
        this.titleTemplates.push({ value: "" }, { value: "" });

        break;
      case 3:
        this.titleTemplates.length = 0
        this.titleTemplates.push({ value: "" }, { value: "" }, { value: "" });

        break;
      case 4:
        this.titleTemplates.length = 0
        this.titleTemplates.push({ value: "" }, { value: "" }, { value: "" }, { value: "" });

        break;
      case 5:
        this.titleTemplates.length = 0
        this.titleTemplates.push({ value: "" }, { value: "" }, { value: "" }, { value: "" }, { value: "" });

        break;
    }
    console.log(this.titleTemplates.length)
    console.log(this.titleTemplates)
  }

  // 保存按钮 更新文档结构解析配置
  updateConfig() {
    if (this.switchValue == true) {
      this.titleData = [];
      this.saveisTitle = false;
    } else {
      this.saveisTitle = true;
      // 将对象titleTemplates 转换成字符串
      let arr = []
      let istrueOne = false
      this.titleTemplates.forEach(i => {
        i.value = i.value.replace(/^\s+|\s+$/g,"")
        if (i.value === '') {
          this.islength = true
          istrueOne = true
        }
        if(istrueOne == false){
            arr.push(i.value)
            this.islength = false  
        }
      })
      arr.join()
      this.titleData = arr
      if (this.islength == true) {
        return this.message.error('标题不能为空')
      }
      console.log(this.titleData)
    }
    // 项目id
    let id = sessionStorage.getItem('id');
    this.http.post('/contract-extraction/extraction-mgr/update-doc-config', {
      project_id: id,
      doc_config: {
        title_depth: this.titleLevel,
        is_remove_category: this.category,
        is_remove_header_footer: this.headerFooter,
        title_split_by_colon: this.splitColon,
        title_templates: this.titleData
      }
    }).then((res: any) => {
      console.log(res)
      if (this.saveisTitle == false) {
        // 开启标题等级自动挖掘
        this.switchValue = true
      }
      this.message.success("保存成功!")
    }).catch((err: any) => {
      this.message.error(err.error_msg);
    })
  }
  // 测试 文件
  runConfig() {
    this.exportFileBase64 = "";
    // 显示模态框
    this.Modalstructu = true;
    // 将下拉选择器 关闭
    this.selectModel = false
    // 清空多选数据
    this.checkOptionsOne = []
    // 清空选择回显的name 
    this.selectorName = [];
    // 清空id
    this.selectorId = [];
    // 清空数据
    this.Jobcontent = [];
    // 如果全选按钮已经选择上了 那就取消掉
    this.master = false
    // 清空搜索输入框
    this.seekFileValueOne = ''
    // 获取文件列表
    // 项目id
    let id = sessionStorage.getItem('id');
    this.http.post('/contract-extraction/data-mgr/query-all-processed-file', {
      project_id: id
    }).then((res: any) => {
      console.log(res)
      this.checkOptionsOne = res.result
      this.checkOptionsOneList = res.result
      // 给文件选择器列表 传进去一个boolean值
      this.checkOptionsOne.forEach((i: any) => {
        i.checked = false
      });
      this.checkOptionsOneList.forEach((i: any) => {
        i.checked = false
      });
    }).catch((err: any) => {
      this.message.error(err.error_msg);
    })
  }
  // 文档结构解析测试文件搜索
  seekFileOne(){
    this.seekFileValueOne = this.seekFileValueOne.replace(/^\s+|\s+$/g,"")
    this.checkOptionsOne = this.checkOptionsOneList
    let arr = []
    this.checkOptionsOne.forEach(e => {
      if(e.file_name.includes(this.seekFileValueOne)){
        arr.push(e)
      }
    });
    if(this.seekFileValueOne == ''){
      this.checkOptionsOne = this.checkOptionsOneList
    }else{
      this.checkOptionsOne = arr
    }
  }
  // 开始测试按钮 测试文档结构解析
  TestStart() {
    // 如果多选框已经是true 就把他隐藏
    if (this.selectModel == true) {
      this.selectModel = false
    }
    // 将对象titleTemplates 转换成字符串
    if (this.switchValue == true) {
      // this.titleTemplates = [];
      this.titleData = [];
      this.saveisTitle = false;
    } else {
      this.saveisTitle = true;
      //   // 将对象titleTemplates 转换成字符串
      let arr = []
      this.titleTemplates.forEach(i => {
        if (i.value === '') {
          this.islength = true
          console.log(213321321)
        }
        if (i.value != '') {
          arr.push(i.value)
          this.islength = false
          console.log("执行了")
        }
      })
      arr.join()
      this.titleData = arr
      if (this.islength == true) {
        return this.message.error('标题不能为空')
      }
      console.log(this.titleData)
    }
    // 项目id
    let id = sessionStorage.getItem('id');
    this.http.post('/contract-extraction/extraction-mgr/run-doc-config', {
      project_id: id,
      title_depth: this.titleLevel,//标题级数
      is_remove_category: this.category,//移除目录
      is_remove_header_footer: this.headerFooter,//移除页眉页脚
      title_split_by_colon: this.splitColon,// 对标题中的冒号进行切割
      file_list: this.selectorId,//选中文件的id列表
      title_templates: this.titleData
    }).then((res: any) => {
      console.log(res)
      if (res && res.error_code == "AIS.0000") {
        this.JobTestId = res.result.job_id
        this.getTestJob();
        this.message.success("测试文件上传成功，请等待测试结果！");
      } else if (res && res.error_code != "AIS.0000") {
        this.message.error("测试文件上传失败，请重试");
      }
    }).catch((err: any) => {
      this.message.error(err.error_msg);
    })

  }
  // job查询
  getTestJob() {
    let that = this;
    that.jobTimer = setInterval(function () {
      that.http.post('/contract-extraction/job-mgr/query-job', {
        job_id: that.JobTestId
      }).then((res: any) => {
        if (res.result) {
          if (res.result.job_status == "success") {

            that.Jobcontent = res.result.job_result.content
            that.exportFileBase64 = res.result.job_result.export_file_base64
            that.exportFileName = res.result.job_result.export_filename;
            that.message.success("成功获取测试结果！");
            that.clearTestJob()
          } else if (res.result.job_status == "waiting") {
            that.message.info(that.JobTestId + "正在排队等待，请稍后！");
          } else if (res.result.job_status == "running") {
            that.message.info(that.JobTestId + "正在查询，请稍后！");
          } else {
            that.message.error(that.JobTestId + "查询失败，请重试！");
            that.clearTestJob()
          }
        }
        else {
          that.message.error(that.JobTestId + "轮询查询失败，请重试！");
          that.clearTestJob()
        }
      }).catch((data: any) => {
        that.message.error(that.JobTestId + data.error_msg);
        that.clearTestJob()
      })
    }, 3000);
  }

  clearTestJob() {
    if (this.jobTimer != null) {
      clearInterval(this.jobTimer)
    }
  }

  downLoad() {
    if (this.exportFileBase64 == null || this.exportFileBase64 == "") {
      this.message.error("尚未获取到文件，请稍后再试！");
      return;
    }
    let base64Pdf = this.exportFileBase64;
    const arrayBuffer = this.dataURLtoBlob(base64Pdf); // 创建Array缓冲区
    this.createAndDownloadBlobFile(arrayBuffer, this.exportFileName);
  }

  //**dataURL to blob** 
  dataURLtoBlob(dataurl) {
    // var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1], 
    //     bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); 
    // while (n--) { 
    //     u8arr[n] = bstr.charCodeAt(n); 
    // } 
    // return new Blob([u8arr], { type: mime }); 
    const binaryString = window.atob(dataurl); //如果不使用base64，则注释这个
    const bytes = new Uint8Array(binaryString.length);
    return bytes.map((byte, i) => binaryString.charCodeAt(i));
  }

  createAndDownloadBlobFile(body, filename) {
    const blob = new Blob([body]);
    const fileName = `${filename}`;
    if (navigator.msSaveBlob) {
      // IE 10+
      navigator.msSaveBlob(blob, fileName);
    } else {
      const link = document.createElement('a');
      //支持HTML5下载属性的浏览器
      if (link.download !== undefined) {
        const url = URL.createObjectURL(blob);
        link.setAttribute('href', url);
        link.setAttribute('download', fileName);
        link.style.visibility = 'hidden';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      }
    }
  }
  // 查询文档抽取标签列表
  getAnalysisTag() {
    // 项目id
    let id = sessionStorage.getItem('id');
    this.http.post('/contract-extraction/extraction-mgr/query-extraction-label', {
      project_id: id
    }).then((res: any) => {
      if(res && res.result != ''){
        this.AnalysisTagList = res.result
        // 搜索的列表的data 需要多赋值一遍
        this.seekTagList = res.result
        console.log(this.AnalysisTagList)
        // 如果只有一个标签  默认获取第一个的标签抽取配置
        if (this.AnalysisTagList.length > 0) {
          this.getOneTagConfig()
      }
      }else{
        this.message.error("标签列表为空!")
      }
      
    }).catch((err: any) => {
      this.message.error(err.error_msg);
    })
  }
  // 搜索标签
  seekTag(){
    this.seekTagValue = this.seekTagValue.replace(/^\s+|\s+$/g,"")
    this.AnalysisTagList =  this.seekTagList
    let arr = []
    this.AnalysisTagList.forEach(e => {
      if(e.label_name.includes(this.seekTagValue)){
        arr.push(e)
      }
    });
    if(this.seekTagValue == ''){
      this.AnalysisTagList =  this.seekTagList
    }else{
      this.AnalysisTagList = arr
    }
  }
  // 获取标签抽取配置
  getTagConfig(e, index) {     
    // 将拿到的数据赋值给对应的data 后期做相应的操作
    // 点亮选择的label
    this.selectLabel = index
    this.TagName = e.label_name;
    this.TagId = e.label_id;
    console.log(this.TagId)
    this.http.post('/contract-extraction/extraction-mgr/query-label-config', {
      label_id: e.label_id
    }).then((res: any) => {
      // console.log(res)
      // this.AnalysisTagList[index].istrue = true;
      // 判断后台是否给返回了空的title数据
      if (Object.keys(res.result.title_config).length == 0) {
        // 如果返回的数据为空 就执行这个方法 向页面渲染一个空的title输入框
        let titleArr = {
          is_reverse: true,
          search_patterns: [
            { value: "" }
          ]
        }
        res.result.title_config = titleArr
        this.TitleList = res.result.title_config
      } else {
        // 如果返回的数据不是空 就渲染返回的数据
        // 解析返回的title数据
        let search_patternsArr = [];
        res.result.title_config.search_patterns.map(i => {
          let obj = {
            value: i
          }
          search_patternsArr.push(obj)
        })
        res.result.title_config.search_patterns = search_patternsArr
        this.TitleList = res.result.title_config
      }
      // 判断后台是否给返回的空的工作流数据
      if (res.result.content_config.length == 0) {
        // 清空数据 重新赋值
        this.ModelDataList = []
        this.workflowList = []
        return
      } else {
        // 如果后台返回了内容 则将数据渲染页面
        // 解析返回的工作流数据
        let ops = []
        // 模型工作流
        let Modelarr = []
        // 清空数据 重新赋值
        this.ModelDataList = []
        this.workflowList = []
        // 把后台的数据赋值给一个变量
        let resList = res.result.content_config
        resList.forEach(e => {
          // console.log(e.ops)
          if (e.ops) {
            ops.push(e)
            e.ops.forEach(e => {
              e.isAble = false
            })
          }
          if (e.workflow_type == 'model') {
            Modelarr.push(e)
          }
        });
        // 赋值后台返回的modelop
        this.ModelDataList = Modelarr
        // 解析后台返回的ops 
        console.log(ops)
        this.workflowList = ops;
        // console.log(this.workflowList)
        this.WorkflowId = res.result.content_config.workflow_id
      }
      // 每次获取完标签配置 显示标题检索为点击编辑状态
      this.activeStatus = true
    }).catch((err: any) => {
      this.message.error(err.error_msg);
    })
  }
  // 默认获取第一个的标签抽取配置
  getOneTagConfig() {
    // 如果是新建标签 获取新建标签的数据 如果不是新建标签 哪就默认获取第一条的数据
    if(this.addLabelId == null){
      this.OneLabelId = this.AnalysisTagList[0].label_id
    }else{
      this.OneLabelId = this.addLabelId
    }
    this.http.post('/contract-extraction/extraction-mgr/query-label-config', {
      label_id: this.OneLabelId
    }).then((res: any) => {
      console.log("调用了此方法")
      // 判断后台是否给返回了空的title数据
      if (Object.keys(res.result.title_config).length == 0) {
        // 如果返回的数据为空 就执行这个方法 向页面渲染一个空的title输入框
        let titleArr = {
          is_reverse: true,
          search_patterns: [
            { value: "" }
          ]
        }
        res.result.title_config = titleArr
        this.TitleList = res.result.title_config
      } else {
        // 如果返回的数据不是空 就渲染返回的数据
        //解析返回的title数据
        let search_patternsArr = [];
        res.result.title_config.search_patterns.map(i => {
          let obj = {
            value: i
          }
          search_patternsArr.push(obj)
        })
        res.result.title_config.search_patterns = search_patternsArr
        this.TitleList = res.result.title_config
      }
      // 判断后台是否给返回的空的工作流数据
      if (res.result.content_config.length == 0) {
        // 清空数据 重新赋值
        this.ModelDataList = []
        this.workflowList = []
        return
      } else {
        // 如果后台返回了内容 则将数据渲染页面
        // 解析返回的工作流数据
        let ops = []
        // 模型工作流
        let Modelarr = []
        // 清空数据 重新赋值
        this.ModelDataList = []
        this.workflowList = []
        // 把后台的数据赋值给一个变量
        let resList = res.result.content_config
        resList.forEach(e => {
          // console.log(e.ops)
          if (e.ops) {
            ops.push(e)
            e.ops.forEach(e => {
              e.isAble = false
            })
          }
          if (e.workflow_type == 'model') {
            Modelarr.push(e)
          }
        });
        // 赋值后台返回的modelop
        this.ModelDataList = Modelarr
        console.log(this.ModelDataList)
        // 解析后台返回的ops 
        this.workflowList = ops;
        console.log(this.workflowList)
        this.WorkflowId = res.result.content_config.workflow_id
      }
      // 每次获取完标签配置 显示标题检索为点击编辑状态
      this.activeStatus = true
    }).catch((err: any) => {
      this.message.error(err.error_msg);
    })
  }
  // 新建标签弹窗
  addTagModel() {
    this.addTagModelShow = true;
    this.addTagValue = '';
  }

  // 添加文档抽取标签 
  addTag() {
    let newArray = this.AnalysisTagList.map(e => e.label_name);
    if (newArray.includes(this.addTagValue)) {
      this.message.error(this.addTagValue + '已经存在!');
      return;
    }
    this.addTagValue= this.addTagValue.replace(/^\s+|\s+$/g,"")
    if(this.addTagValue == ''){
      return this.message.error("新建标签不能为空!")
    }
    //项目id
    let id = sessionStorage.getItem('id');
    this.http.post('/contract-extraction/extraction-mgr/add-extraction-label', {
      project_id: id,
      label_name: this.addTagValue
    }).then((res: any) => {
      console.log(res)
      if(res&& res.result && res.result.label_id){
        this.addLabelId = res.result.label_id
        this.message.success("添加标签成功！")
      }else{
        this.message.error("添加标签失败！")
      }
      // 查询文档抽取标签列表
      this.getAnalysisTag()
      // 关闭弹窗
      this.addTagModelShow = false;
    }).catch((err: any) => {
      this.message.error(err.error_msg);
    })
  }
  // 删除标签弹窗
  deleteTag(data) {
    this.deleteTagShow = true;
    this.editLabelId = data.label_id
  }
  // 删除文档抽取标签
  deleteTagOk() {
    this.http.post('/contract-extraction/extraction-mgr/delete-extraction-label', {
      label_id: this.editLabelId
    }).then((res: any) => {
      console.log(res)
      // 查询文档抽取标签列表
      this.getAnalysisTag()
      // 关闭模态框
      this.deleteTagShow = false
    }).catch((err: any) => {
      this.message.error(err.error_msg);
    })
  }
  // 编辑标签弹窗
  editTagModel(data) {
    console.log(data)
    this.editTagModelShow = true;
    this.editTagValue = data.label_name
    this.editLabelId = data.label_id
  }
  // 更新文档抽取标签名称
  updatTagTitle() {
    this.editTagValue = this.editTagValue.replace(/^\s+|\s+$/g,"")
    let newArray = this.AnalysisTagList.map(e => {
      if(this.editLabelId != e.label_id)
      return e.label_name
    });
    if (newArray.includes(this.editTagValue)) {
      this.message.error(this.editTagValue + '已经存在!');
      return;
    }
    if(this.editTagValue == ''){
      return this.message.error("编辑名称不能为空!")
    }
    this.http.post('/contract-extraction/extraction-mgr/update-extraction-label', {
      label_id: this.editLabelId,
      label_name: this.editTagValue
    }).then((res: any) => {
      console.log(res)
      // 查询文档抽取标签列表
      this.getAnalysisTag()
      // 关闭模态框
      this.editTagModelShow = false
    }).catch((err: any) => {
      this.message.error(err.error_msg);
    })
  }
  // 添加标题
  addTitle(Sindex) {
    console.log(this.TitleList)
    if (this.TitleList && this.TitleList.search_patterns) {
      if (this.TitleList.search_patterns.length < 5)
        this.TitleList.search_patterns.push({ value: "" })
      else {
        this.message.error("最多只能添加五级标题");
      }
    }
    else {
      this.message.error("请先选择左侧标签");
    }
  }
  // 标题级数
  getlength(index) {
    switch (index) {
      case 1: return '一'
        break;
      case 2: return '二'
        break;
      case 3: return '三'
        break;
      case 4: return '四'
        break;
      case 5: return '五'
        break;
    }
  }
  // 删除标题
  deleteTitle(index, Sindex) {
    if (this.activeStatus == false) {
      this.TitleList.search_patterns.splice(Sindex, 1)
    } else {
      return this.message.error("请先点击编辑!")
    }

    console.log(Sindex)
  }
  // 更新标签title-config
  updatTitleConfig() {
    if (this.TagId == undefined) {
      this.TagId = this.AnalysisTagList[0].label_id
    }
    // 请求体解析成字符串
    let arr = []
    let arrTitle = this.TitleList.search_patterns
    let istrue = false
    arrTitle.map(i => {
      i.value = i.value.replace(/^\s+|\s+$/g,"")
      if (i.value == '') {
        this.message.error('标题检索不能为空!')
        istrue = true
        return
      } else {
        arr.push(i.value)
      }
    })
    if (istrue == false) {
      let title_config = {
        "is_reverse": this.TitleList.is_reverse,
        "search_patterns": arr
      }
      console.log(arr)
      console.log(this.TagId)
      this.http.post('/contract-extraction/extraction-mgr/update-title-config', {
        label_id: this.TagId,
        title_config: title_config
      }).then((res: any) => {
        console.log(res)
        if (res && res.error_code && res.error_code == "AIS.0000") {
          this.message.success("保存成功！");
          this.activeStatus = true
        } else {
          this.message.error("保存失败，请稍后再试！");
        }
      }).catch((err: any) => {
        this.message.error(err.error_msg);
      })
    }
  }
  // 添加标签workflow  //返回 workflow_id
  addWorkflow() {
    if (this.TagId == undefined) {
      this.TagId = this.AnalysisTagList[0].label_id
    }
    console.log(this.TagId)
    this.http.post('/contract-extraction/extraction-mgr/add-workflow', {
      label_id: this.TagId,
      type: "rule"
    }).then((res: any) => {
      console.log(res)
      // 将后台返回的id 动态添加到workflowList数组里
      this.workflowList.push({ workflow_id: res.result.workflow_id, ops: [] })
      console.log(this.workflowList)
    }).catch((err: any) => {
      this.message.error(err.error_msg);
    })
    console.log(this.workflowList)
  }

  // 删除标签的workflow 
  deleteWorkflow(index, id) {
    // 弹出删除框
    this.deleteWorkflowShow = true;
    // 点击删除拿到的id
    this.deleteWorkflowId = id;
    // 赋值index
    this.deleteIndex = index
    console.log(this.workflowList[this.deleteIndex])
  }
  // 取消删除工作流
  deleteshut() {
    this.deleteWorkflowShow = false;
    this.addTagModelShow = false;
    this.editTagModelShow = false;
    this.deleteTagShow = false;
    this.deleteWorkOpShow = false;
    this.deleteModelWorkShow = false;
    this.ShowDataValue = false;
  }
  // 确定删除工作流
  deleteOk() {
    console.log(this.deleteWorkflowId)
    this.http.post('/contract-extraction/extraction-mgr/delete-workflow', {
      workflow_id: this.deleteWorkflowId
    }).then((res: any) => {
      console.log(res)
      this.deleteWorkflowShow = false;
      // this.getTagConfig()
      this.workflowList.splice(this.deleteIndex, 1)
      // let labelId = null;
      // // 如果以后没有主动点击获取标签 那就默认删除第一个
      // if(this.TagId == undefined){
      //   labelId = this.AnalysisTagList[0].label_id
      // }else{
      //   // 如果用户主动点击了获取标签 那就给他主动点击的标签id
      //   labelId = this.TagId
      // }
      // // 获取标签配置
      // this.http.post('/contract-extraction/extraction-mgr/query-label-config',{
      //   label_id:labelId
      // }).then((res:any)=>{
      //   console.log(res)
      //   console.log(labelId)
      //   console.log("标签配置接口调用了")
      //     // 如果后台返回了内容 则将数据渲染页面
      //     // 解析返回的工作流数据
      //     let ops = []
      //     res.result.content_config.forEach(e => {
      //       console.log(e.ops)
      //       if (e.ops) {
      //         ops.push(e)
      //         e.ops.forEach(e => {
      //           e.isAble = false
      //         })
      //       }
      //   });
      //   // 解析后台返回的ops 
      //   this.workflowList = ops;
      //   console.log(this.workflowList)
      //   this.WorkflowId = res.result.content_config.workflow_id
      // })
    }).catch((err: any) => {
      this.message.error(err.error_msg);
    })
  }
  // 添加规则按钮 添加工作流OP 
  addRule(index) {
    // 添加一条死数据
    console.log(index)
    this.workflowList[index].ops.push({
      op: "search",
      type: "first-search",
      isAble: true,
      pattern: '',
      op_id: ''
    })
    console.log(this.workflowList[index])
    console.log(this.workflowList)
  }
  // 编辑规则按钮
  editWorkflow(index, sindex) {
    // 选择器默认是禁用 点击编辑 编辑按钮隐藏 更新按钮显示 选择器取消禁用
    // 选择器禁用取消
    this.workflowList[index].ops[sindex].isAble = true;
  }
  // 更新工作流中的OP 
  updateOperator(index, sindex, id) {
    console.log(id)
    // 如果op id为空 就走添加接口
    if (id == '') {
      if (this.workflowList[index].ops[sindex].op === 'search') {
        this.http.post('/contract-extraction/extraction-mgr/add-operator', {
          workflow_id: this.workflowList[index].workflow_id,
          op_config: {
            op: this.workflowList[index].ops[sindex].op,
            type: this.workflowList[index].ops[sindex].type,
            pattern: this.workflowList[index].ops[sindex].pattern,
          }
        }).then((res: any) => {
          console.log(res)
          // 把后台返回的id 传到数组里
          if (res && res.result && res.result.op_id) {
            this.workflowList[index].ops[sindex].op_id = res.result.op_id
            this.message.success("添加成功!")
          } else {
            this.message.error("添加失败!")
          }
          // 更新成功后 将选择器状态转换为禁用 显示编辑按钮
          this.workflowList[index].ops[sindex].isAble = false;
        }).catch((err: any) => {
          this.message.error(err.error_msg);
        })
      } else if (this.workflowList[index].ops[sindex].op === 'filter') {
        this.http.post('/contract-extraction/extraction-mgr/add-operator', {
          workflow_id: this.workflowList[index].workflow_id,
          op_config: {
            op: this.workflowList[index].ops[sindex].op,
            type: this.workflowList[index].ops[sindex].type,
            keywords: this.workflowList[index].ops[sindex].keywords,
          }
        }).then((res: any) => {
          console.log(res)
          // 把后台返回的id 传到数组里
          if (res && res.result && res.result.op_id) {
            this.workflowList[index].ops[sindex].op_id = res.result.op_id
            this.message.success("添加成功!")
          } else {
            this.message.error("添加失败!")
          }
          // 更新成功后 将选择器状态转换为禁用 显示编辑按钮
          this.workflowList[index].ops[sindex].isAble = false;
        }).catch((err: any) => {
          this.message.error(err.error_msg);
        })
      } else {
        this.http.post('/contract-extraction/extraction-mgr/add-operator', {
          workflow_id: this.workflowList[index].workflow_id,
          op_config: {
            op: this.workflowList[index].ops[sindex].op,
            type: this.workflowList[index].ops[sindex].type,
          }
        }).then((res: any) => {
          console.log(res)
          // 把后台返回的id 传到数组里
          if (res && res.result && res.result.op_id) {
            this.workflowList[index].ops[sindex].op_id = res.result.op_id
            this.message.success("添加成功!")
          } else {
            this.message.error("添加失败!")
          }
          // 更新成功后 将选择器状态转换为禁用 显示编辑按钮
          this.workflowList[index].ops[sindex].isAble = false;
        }).catch((err: any) => {
          this.message.error(err.error_msg);
        })
      }
    } else {
      // 如果opid不为空 就走更新接口
      if (this.workflowList[index].ops[sindex].op === 'search') {
        // id 不为空就走 保存的接口
        this.http.post('/contract-extraction/extraction-mgr/update-operator', {
          op_id: id,
          op_config: {
            op: this.workflowList[index].ops[sindex].op,
            type: this.workflowList[index].ops[sindex].type,
            pattern: this.workflowList[index].ops[sindex].pattern,
          }
        }).then((res: any) => {
          console.log(res)
          if (res.error_code == 'AIS.0000') {
            this.message.success("更新成功!")
            // 更新成功后 将选择器状态转换为禁用 显示编辑按钮
            this.workflowList[index].ops[sindex].isAble = false;
          } else {
            this.message.error("更新失败!")
          }
        }).catch((err: any) => {
          this.message.error(err.error_msg);
        })
      } else if (this.workflowList[index].ops[sindex].op === 'filter') {
        this.message.success("关键词检测")
        // id 不为空就走 保存的接口
        this.http.post('/contract-extraction/extraction-mgr/update-operator', {
          op_id: id,
          op_config: {
            op: this.workflowList[index].ops[sindex].op,
            type: this.workflowList[index].ops[sindex].type,
            keywords: this.workflowList[index].ops[sindex].keywords,
          }
        }).then((res: any) => {
          console.log(res)
          if (res.error_code == 'AIS.0000') {
            // 更新成功后 将选择器状态转换为禁用 显示编辑按钮
            this.workflowList[index].ops[sindex].isAble = false;
          } else {
            this.message.error("更新失败!")
          }
        }).catch((err: any) => {
          this.message.error(err.error_msg);
        })
      } else {
        // id 不为空就走 保存的接口
        this.http.post('/contract-extraction/extraction-mgr/update-operator', {
          op_id: id,
          op_config: {
            op: this.workflowList[index].ops[sindex].op,
            type: this.workflowList[index].ops[sindex].type
          }
        }).then((res: any) => {
          console.log(res)
          if (res.error_code == 'AIS.0000') {
            this.message.success("更新成功!")
            // 更新成功后 将选择器状态转换为禁用 显示编辑按钮
            this.workflowList[index].ops[sindex].isAble = false;
          } else {
            this.message.error("更新失败!")
          }
        }).catch((err: any) => {
          this.message.error(err.error_msg);
        })
      }

    }


  }
  // 操作选择器拿到的
  operationSelect(value, pIndex, cIdnex): void {
    this.workflowList[pIndex].ops[cIdnex].op = value;
    // 操作选择器 对应类型
    if (value === 'search') {
      this.workflowList[pIndex].ops[cIdnex].type = 'first-search'
    } else if (value === 'split') {
      this.workflowList[pIndex].ops[cIdnex].type = 'paragraph'
    } else {
      this.workflowList[pIndex].ops[cIdnex].type = 'keep'
    }
  }
  // 类型选择器拿到的
  typeSelect(value): void {
    // console.log(value)
    // console.log(this.workflowList)
    // console.log(this.workflowList[0].ops)
    // console.log(this.selectedCity)
  }

  // 删除工作流中的OP  
  deleteOperator(index, sindex, id) {
    console.log(this.workflowList[index].ops[sindex].isAble)
    //  显示模态框
    this.deleteWorkOpShow = true;
    // op ID
    this.deleteWorkOpId = id
    this.workOpIndex = index
    this.workOpSindex = sindex
    console.log(this.workOpIndex)
    console.log(this.workOpSindex)
    console.log(this.deleteWorkOpId)
  }
  // 确定删除op工作流
  deleteWorkOk() {
    console.log(this.workflowList[this.workOpIndex].ops[this.workOpSindex])
    if (this.deleteWorkOpId == '') {
      this.workflowList[this.workOpIndex].ops.splice(this.workOpSindex, 1)
      // 隐藏模态框
      this.deleteWorkOpShow = false
    } else {
      this.http.post('/contract-extraction/extraction-mgr/delete-operator', {
        op_id: this.deleteWorkOpId
      }).then((res: any) => {
        console.log(res)
        this.workflowList[this.workOpIndex].ops.splice(this.workOpSindex, 1)
        // 隐藏模态框
        this.deleteWorkOpShow = false
      }).catch((err: any) => {
        this.message.error(err.error_msg);
      })
    }
  }


  onChange($event: string[]): void {
    console.log($event);
  }
  // 点击添加模型工作流 显示模态框
  ShowModalWork(): void {
    this.Modalwork = true;
    let id = sessionStorage.getItem('id');
    this.http.post('/contract-extraction/model-mgr/query-all-model', {
      project_id: id
    }).then((res: any) => {
      console.log(res)
      this.listOfData = res.result
    }).catch((err: any) => {
      this.message.error(err.error_msg);
    })
  }
  // 添加模型工作流 tab表格选择器
  ModelSelect(data) {
    // console.log(data)
    this.selectModelData = data
    console.log(this.selectModelData)
  }
  //添加模型工作流modal确定
  workModalOk() {
    //如果这个id 为空 默认就是第一label 
    if (this.TagId == undefined) {
      this.TagId = this.AnalysisTagList[0].label_id
    }
    this.http.post('/contract-extraction/extraction-mgr/add-workflow', {
      label_id: this.TagId,
      type: "model",
      model_id: this.selectModelData.model_id,
    }).then((res: any) => {
      console.log(res)
      if (res && res.result && res.result.workflow_id) {
        this.selectModelData.workflow_id = res.result.workflow_id;
        this.ModelDataList = [...this.ModelDataList, this.selectModelData]
        this.message.success("添加模型工作流成功!")
        this.Modalwork = false
      } else {
        this.message.error("添加模型工作流失败!")
      }
    }).catch((err: any) => {
      this.message.error(err.error_msg);
    })
  }
  //添加模型工作流modal取消
  workModalCancel() {
    this.Modalwork = false
  }
  // 删除模型工作流 workflow
  deleteModelWorkflow(index, id) {
    this.deleteModelIndex = index
    this.deleteModelId = id
    // 打开模态框
    this.deleteModelWorkShow = true
  }
  // 删除工作流 确定
  deleteModelWorkOk() {
    this.http.post('/contract-extraction/extraction-mgr/delete-workflow', {
      workflow_id: this.deleteModelId
    }).then((res: any) => {
      console.log(res)
      // 关闭模态框
      this.deleteModelWorkShow = false
      this.ModelDataList.splice(this.deleteModelIndex, 1)
    })
  }
  // 确认按钮
  handleOk(): void {
    console.log('Button ok clicked!');
    this.Modalwork = false;
  }
  // 取消按钮
  handleCancel(): void {
    console.log('Button cancel clicked!');
    this.Modalwork = false;
  }

  // 取消
  TestCancel(): void {
    this.Modaltest = false;
    this.Modalstructu = false;
    this.ModalWorkflow = false;
    this.ModalWorkflowShow = false;
  }
  // 点击选择测试文件弹出
  ShowSelectModal(): void {
    this.selectModel = true;
  }
  // 确定
  selectOk(): void {
    this.selectModel = false;
  }
  // 取消
  // selectCancel(): void {
  //   this.selectorName = [];
  //     this.selectorId = [];
  //     this.checkOptionsOne.forEach((i, index) => {
  //       i.checked = false
  //     });
  //   this.selectModel = false;
  // }
  //改变标题检索模块 规则活动态
  changeActiveStatus() {
    this.activeStatus = false
  }
  // 文档结构解析 全选
  checkAll() {
    this.selectorName = [];
    this.selectorId = [];
    // 判断是否全选超过100
    // if(this.selectorName.length < 1){
    if (this.master === true) {
      this.checkOptionsOne.forEach((i, index) => {
        console.log(i)
        this.selectorName.push(i.file_name)
        this.selectorId.push(i.file_id)
        i.checked = true
      });
      console.log(this.selectorName)
      console.log(this.selectorId)
    } else {
      console.log('到这步了')
      this.selectorName = [];
      this.selectorId = [];
      this.checkOptionsOne.forEach((i, index) => {
        i.checked = false
      });
    }
  }
  // 单独选择的文件
  selectSingle(id, name, index, checked) {
    console.log(index)

    if (checked === true) {

      if (this.selectorName.indexOf(name) == -1 && this.selectorId.indexOf(id) == -1) {
        this.selectorName.push(name)
        this.selectorId.push(id)
      }
      if (this.selectorId.length == this.checkOptionsOne.length) {
        this.master = true
      }
    } else {
      this.selectorId.map((i, index) => {
        console.log(i)
        if (i.includes(id)) {
          this.selectorName.splice(index, 1)
          this.selectorId.splice(index, 1)
        }
      })
      if (this.selectorId.length < this.checkOptionsOne.length) {
        this.master = false
      }
    }
  }
  getSelectorName() {
    return this.selectorName.join(';')
  }
  showModalTest(): void {
    this.Modaltest = true
  }

  // 点击label测试按钮 显示模态框
  ShowTestModal(e): void {
    this.exportFileBase64 = "";
    // 多选清空
    this.checkOptionsTwo = [];
    // name列表
    this.selectorConfigName = [];
    // id列表
    this.selectorConfigId = [];
    // 将下拉选择器 关闭
    this.selectConfigModel = false
    // 渲染到的数据 
    this.conifgJobcontent = []
    // 关闭多选按钮状态
    this.configMaster = false
    // 清空搜索输入框
    this.seekFileValueTwo = ''
    this.testLabelId = e.label_id;
    let id = sessionStorage.getItem('id');
    this.http.post('/contract-extraction/data-mgr/query-all-processed-file', {
      project_id: id
    }).then((res: any) => {
      console.log(res)
      this.checkOptionsTwo = res.result
      // 给文件选择器列表 传进去一个boolean值
      this.checkOptionsTwo.forEach((i: any) => {
        i.checked = false
      });
      this.checkOptionsTwoList = res.result
      // 给文件选择器列表 传进去一个boolean值
      this.checkOptionsTwoList.forEach((i: any) => {
        i.checked = false
      })
    }).catch((err: any) => {
      this.message.error(err.error_msg);
    })

    this.http.post('/contract-extraction/extraction-mgr/query-label-config', {
      label_id: e.label_id
    }).then((res: any) => {
      if (res.result && res.result.content_config) {
        this.testWorkFlowIds = [];
        res.result.content_config.forEach(workflow => {
          this.testWorkFlowIds.push(workflow.workflow_id)
        });
      }
    }).catch((err: any) => {
      this.message.error(err);
    })

    this.Modaltest = true;
  }
  // 抽取配置标签测试文件搜索
  seekFileTwo(){
    this.seekFileValueTwo = this.seekFileValueTwo.replace(/^\s+|\s+$/g,"")
    this.checkOptionsTwo = this.checkOptionsTwoList
    let arr = []
    this.checkOptionsTwo.forEach(e => {
      if(e.file_name.includes(this.seekFileValueTwo)){
        arr.push(e)
      }
    });
    if(this.seekFileValueTwo == ''){
      this.checkOptionsTwo = this.checkOptionsTwoList
    }else{
      this.checkOptionsTwo = arr
    }
  }


  ShowSelectConfigModal() {
    this.selectConfigModel = true;
  }

  getSelectorConfigName() {
    return this.selectorConfigName.join(';')
  }

  // 全选
  checkConfigAll() {
    this.selectorConfigName = [];
    this.selectorConfigId = [];
    // 判断是否全选超过100
    // if(this.selectorName.length < 1){
    if (this.configMaster === true) {
      this.checkOptionsTwo.forEach((i, index) => {
        console.log(i)

        this.selectorConfigName.push(i.file_name)
        this.selectorConfigId.push(i.file_id)
        i.checked = true
      });
      console.log(this.selectorConfigName)
      console.log(this.selectorId)
    } else {
      console.log('到这步了')
      this.selectorConfigName = [];
      this.selectorConfigId = [];
      this.checkOptionsTwo.forEach((i, index) => {
        i.checked = false
      });
    }
  }
  // 单独选择的文件
  selectConfigSingle(id, name, index, checked) {
    console.log(index)

    if (checked === true) {

      if (this.selectorConfigName.indexOf(name) == -1 && this.selectorConfigId.indexOf(id) == -1) {
        this.selectorConfigName.push(name)
        this.selectorConfigId.push(id)
      }
      if (this.selectorConfigId.length == this.checkOptionsTwo.length) {
        this.configMaster = true
      }
    } else {
      this.selectorConfigId.map((i, index) => {
        console.log(i)
        if (i.includes(id)) {
          this.selectorConfigName.splice(index, 1)
          this.selectorConfigId.splice(index, 1)
        }
      })
      if (this.selectorConfigId.length < this.checkOptionsTwo.length) {
        this.configMaster = false
      }
    }
  }

  // 确定
  selectConfigOk(): void {
    this.selectConfigModel = false;
  }
  // 取消
  // selectConfigCancel(): void {
  //   this.selectConfigModel = false;
  //   this.selectorConfigName = [];
  //     this.selectorConfigId = [];
  //     this.checkOptionsTwo.forEach((i, index) => {
  //       i.checked = false
  //     });
  // }
  // label 开始测试
  TestConfigStart() {
    // 如果多选框已经是true 就把他隐藏
    if (this.selectConfigModel == true) {
      this.selectConfigModel = false
    }
    if (this.selectorConfigId && this.selectorConfigId.length < 1) {
      this.message.error("请先选择需要测试的文件!");
      return;
    }
    // 将对象titleTemplates 转换成字符串
    let arr = []
    this.titleTemplates.forEach((i) => {
      arr.push(i.value)
    })
    arr.join()
    console.log(arr)
    // 项目id
    let id = sessionStorage.getItem('id');
    this.http.post('/contract-extraction/extraction-mgr/run-workflows', {
      label_id: this.testLabelId,
      workflow_id: this.testWorkFlowIds,
      file_list: this.selectorConfigId
    }).then((res: any) => {
      console.log(res)
      if (res && res.error_code == "AIS.0000") {
        this.JobTestId = res.result.job_id

        this.getTestConfigJob();
        this.message.success("文件测试成功，正在获取测试结果，请稍后！");
      } else if (res && res.error_code != "AIS.0000") {
        this.message.error("文件测试失败，请重试");
      }
    }).catch((err: any) => {
      this.message.error(err.error_msg);
    })
  }

  getTestConfigJob() {
    let that = this;
    that.configJobTimer = setInterval(function () {
      that.http.post('/contract-extraction/job-mgr/query-job', {
        job_id: that.JobTestId
      }).then((res: any) => {
        if (res.result) {
          if (res.result.job_status == "success") {

            that.conifgJobcontent = res.result.job_result.content
            that.exportFileBase64 = res.result.job_result.export_file_base64
            that.exportFileName = res.result.job_result.export_filename;
            that.message.success("成功获取测试结果！");
            if (that.configJobTimer != null) {
              clearInterval(that.configJobTimer)
            }
          } else if (res.result.job_status == "waiting") {
            that.message.info(that.JobTestId + "正在排队等待，请稍后！");
          } else if (res.result.job_status == "running") {
            that.message.info(that.JobTestId + "正在查询，请稍后！");
          } else {
            that.message.error(that.JobTestId + "查询失败，请重试！");
            if (that.configJobTimer != null) {
              clearInterval(that.configJobTimer)
            }
          }
        }
        else {
          that.message.error(that.JobTestId + "轮询查询失败，请重试！");
          if (that.configJobTimer != null) {
            clearInterval(that.configJobTimer)
          }
        }
      }).catch((data: any) => {
        that.message.error(that.JobTestId + data.error_msg);
        if (that.configJobTimer != null) {
          clearInterval(that.configJobTimer)
        }
      })
    }, 3000);
  }


  // 测试工作流按钮
  testWorkflow(workflowId) {
    this.singleWorkflowId = workflowId;
    this.exportFileBase64 = "";
    // name 列表
    this.selectorWorkflowName = [];
    // id列表
    this.selectorWorkflowId = [];
    // 全选列表
    this.checkOptionsThree = [];
    // 渲染列表
    this.conifgJobcontent = [];
    // 每次进入 将选择器列表隐藏
    this.selectWorkflowModel = false
    this.ModalWorkflow = true;
    // 每次进入的时候 关闭多选按钮状态
    this.workflowMaster = false
    // 清空搜索输入框
    this.seekFileValueThree = ''
    let id = sessionStorage.getItem('id');
    this.http.post('/contract-extraction/data-mgr/query-all-processed-file', {
      project_id: id
    }).then((res: any) => {
      console.log(res)
      this.checkOptionsThree = res.result
      // 给文件选择器列表 传进去一个boolean值
      this.checkOptionsThree.forEach((i: any) => {
        i.checked = false
      });
      this.checkOptionsThreeList = res.result
      // 给文件选择器列表 传进去一个boolean值
      this.checkOptionsThreeList.forEach((i: any) => {
        i.checked = false
      });
    }).catch((err: any) => {
      this.message.error(err.error_msg);
    })

  }
  // 测试工作流搜索文件
  seekFileThree(){
    this.seekFileValueThree = this.seekFileValueThree.replace(/^\s+|\s+$/g,"")
    this.checkOptionsThree = this.checkOptionsThreeList
    let arr = []
    this.checkOptionsThree.forEach(e => {
      if(e.file_name.includes(this.seekFileValueThree)){
        arr.push(e)
      }
    });
    if(this.seekFileValueThree == ''){
      this.checkOptionsThree = this.checkOptionsThreeList
    }else{
      this.checkOptionsThree = arr
    }
  }

  ShowSelectWorkflowModal() {
    this.selectWorkflowModel = true;
  }

  getSelectorWorkflowName() {
    return this.selectorWorkflowName.join(';')
  }

  // 全选
  checkWorkflowAll() {
    this.selectorWorkflowName = [];
    this.selectorWorkflowId = [];
    // 判断是否全选超过100
    // if(this.selectorName.length < 1){
    if (this.workflowMaster === true) {
      this.checkOptionsThree.forEach((i, index) => {
        console.log(i)

        this.selectorWorkflowName.push(i.file_name)
        this.selectorWorkflowId.push(i.file_id)
        i.checked = true
      });
      console.log(this.selectorWorkflowName)
      console.log(this.selectorWorkflowId)
    } else {
      console.log('到这步了')
      this.selectorWorkflowName = [];
      this.selectorWorkflowId = [];
      this.checkOptionsThree.forEach((i, index) => {
        i.checked = false
      });
    }
  }
  // 单独选择的文件
  selectWorkflowSingle(id, name, index, checked) {
    console.log(index)

    if (checked === true) {

      if (this.selectorWorkflowName.indexOf(name) == -1 && this.selectorWorkflowId.indexOf(id) == -1) {
        this.selectorWorkflowName.push(name)
        this.selectorWorkflowId.push(id)
      }
      if (this.selectorWorkflowId.length == this.checkOptionsThree.length) {
        this.workflowMaster = true
      }
    } else {
      this.selectorWorkflowId.map((i, index) => {
        console.log(i)
        if (i.includes(id)) {
          this.selectorWorkflowName.splice(index, 1)
          this.selectorWorkflowId.splice(index, 1)
        }
      })
      if (this.selectorWorkflowId.length < this.checkOptionsThree.length) {
        this.workflowMaster = false
      }
    }
  }

  // 确定
  selectWorkflowOk(): void {
    this.selectWorkflowModel = false;
  }
  // 取消
  // selectWorkflowCancel(): void {
  //   this.selectWorkflowModel = false;
  //   this.selectorWorkflowName = [];
  //     this.selectorWorkflowId = [];
  //     this.checkOptionsThree.forEach((i, index) => {
  //       i.checked = false
  //     });
  // }
  // 工作流 开始测试
  TestWorkflowStart() {
    if (this.TagId == undefined) {
      this.TagId = this.AnalysisTagList[0].label_id
    }
    if (this.selectWorkflowModel == true) {
      this.selectWorkflowModel = false
    }
    if (this.selectorWorkflowId && this.selectorWorkflowId.length < 1) {
      this.message.error("请先选择需要测试的文件!");
      return;
    }
    console.log(this.TagId)
    this.http.post('/contract-extraction/extraction-mgr/run-workflows', {
      label_id: this.TagId,
      workflow_id: [this.singleWorkflowId],
      file_list: this.selectorWorkflowId
    }).then((res: any) => {
      console.log(res)
      if (res && res.error_code == "AIS.0000") {
        this.JobTestId = res.result.job_id

        this.getTestWorkflowJob();
        this.message.success("文件测试成功，正在获取测试结果，请稍后！");
      } else if (res && res.error_code != "AIS.0000") {
        this.message.error("文件测试失败，请重试");
      }
    }).catch((err: any) => {
      this.message.error(err.error_msg);
    })
  }

  getTestWorkflowJob() {
    let that = this;
    that.workflowJobTimer = setInterval(function () {
      that.http.post('/contract-extraction/job-mgr/query-job', {
        job_id: that.JobTestId
      }).then((res: any) => {
        if (res.result) {
          if (res.result.job_status == "success") {

            that.conifgJobcontent = res.result.job_result.content
            that.exportFileBase64 = res.result.job_result.export_file_base64
            that.exportFileName = res.result.job_result.export_filename;
            that.message.success("成功获取测试结果！");
            if (that.workflowJobTimer != null) {
              clearInterval(that.workflowJobTimer)
            }
          } else if (res.result.job_status == "waiting") {
            that.message.info(that.JobTestId + "正在排队等待，请稍后！");
          } else if (res.result.job_status == "running") {
            that.message.info(that.JobTestId + "正在查询，请稍后！");
          } else {
            that.message.error(that.JobTestId + "查询失败，请重试！");
            if (that.workflowJobTimer != null) {
              clearInterval(that.workflowJobTimer)
            }
          }
        }
        else {
          that.message.error(that.JobTestId + "轮询查询失败，请重试！");
          if (that.workflowJobTimer != null) {
            clearInterval(that.workflowJobTimer)
          }
        }
      }).catch((data: any) => {
        that.message.error(that.JobTestId + data.error_msg);
        if (that.workflowJobTimer != null) {
          clearInterval(that.workflowJobTimer)
        }
      })
    }, 3000);
  }

  // 模型工作流 测试按钮
  testModelModel(wrokflowid) {
    console.log(wrokflowid)
    //打开模态框
    this.ModalWorkflowShow = true
    // 每次进入 将多选列表隐藏
    this.selectModelWorkflowModel = false
    this.exportFileBase64 = "";
    // name 列表
    this.selectorWorkflowName = [];
    // id列表
    this.selectorWorkflowId = [];
    // 渲染列表
    this.conifgJobcontent = [];
    // 每次进入关闭多选状态
    this.ModelworkflowMaster = false
    // 清空搜索输入框
    this.seekFileValueFour = ''
    this.singleWorkflowId = wrokflowid;
    let id = sessionStorage.getItem('id');
    console.log(id)
    this.http.post('/contract-extraction/data-mgr/query-all-processed-file', {
      project_id: id
    }).then((res: any) => {
      console.log(res)
      this.checkOptionsFour = res.result
      // 给文件选择器列表 传进去一个boolean值
      this.checkOptionsFour.forEach((i: any) => {
        i.checked = false
      });
      this.checkOptionsFourList = res.result
      // 给文件选择器列表 传进去一个boolean值
      this.checkOptionsFourList.forEach((i: any) => {
        i.checked = false
      });
    }).catch((err: any) => {
      this.message.error(err.error_msg);
    })
  }
  // 搜索模型测试文件
  seekFileFour(){
    this.seekFileValueFour = this.seekFileValueFour.replace(/^\s+|\s+$/g,"")
    this.checkOptionsFour = this.checkOptionsFourList
    let arr = []
    this.checkOptionsFour.forEach(e => {
      if(e.file_name.includes(this.seekFileValueFour)){
        arr.push(e)
      }
    });
    if(this.seekFileValueFour == ''){
      this.checkOptionsFour = this.checkOptionsFourList
    }else{
      this.checkOptionsFour = arr
    }
  }
  // 显示多选框
  ModelSelectWorkflowModal() {
    this.selectModelWorkflowModel = true;
  }
  // 确定
  selectModelWorkflowOk(): void {
    this.selectModelWorkflowModel = false;
    // this.ModalWorkflow = false;
  }
  // 取消
  // selectModelWorkflowCancel(): void {
  //   this.selectModelWorkflowModel = false;
  //   this.selectorWorkflowName = [];
  //   this.selectorWorkflowId = [];
  //   this.checkOptionsFour.forEach((i, index) => {
  //     i.checked = false
  //   });
  // }
  // 全选
  ModelcheckWorkflowAll() {
    this.selectorWorkflowName = [];
    this.selectorWorkflowId = [];
    // 判断是否全选超过100
    // if(this.selectorName.length < 1){
    if (this.ModelworkflowMaster === true) {
      this.checkOptionsFour.forEach((i, index) => {
        console.log(i)

        this.selectorWorkflowName.push(i.file_name)
        this.selectorWorkflowId.push(i.file_id)
        i.checked = true
      });
      console.log(this.selectorWorkflowName)
      console.log(this.selectorWorkflowId)
    } else {
      console.log('到这步了')
      this.selectorWorkflowName = [];
      this.selectorWorkflowId = [];
      this.checkOptionsFour.forEach((i, index) => {
        i.checked = false
      });
    }
  }
  // 单独选择的文件
  ModelselectWorkflowSingle(id, name, index, checked) {
    console.log(index)

    if (checked === true) {

      if (this.selectorWorkflowName.indexOf(name) == -1 && this.selectorWorkflowId.indexOf(id) == -1) {
        this.selectorWorkflowName.push(name)
        this.selectorWorkflowId.push(id)
      }
      if (this.selectorWorkflowId.length == this.checkOptionsFour.length) {
        this.ModelworkflowMaster = true
      }
    } else {
      this.selectorWorkflowId.map((i, index) => {
        console.log(i)
        if (i.includes(id)) {
          this.selectorWorkflowName.splice(index, 1)
          this.selectorWorkflowId.splice(index, 1)
        }
      })
      if (this.selectorWorkflowId.length < this.checkOptionsFour.length) {
        this.ModelworkflowMaster = false
      }
    }
  }
  getModelSelectorWorkflowName() {
    return this.selectorWorkflowName.join(';')
  }

  // 模型工作流 开始测试
  TestModelWorkflowStart() {
    if (this.TagId == undefined) {
      this.TagId = this.AnalysisTagList[0].label_id
    }
    if (this.selectModelWorkflowModel == true) {
      this.selectModelWorkflowModel = false
    }
    if (this.selectorWorkflowId && this.selectorWorkflowId.length < 1) {
      this.message.error("请先选择需要测试的文件!");
      return;
    }
    this.http.post('/contract-extraction/extraction-mgr/run-workflows', {
      label_id: this.TagId,
      workflow_id: [this.singleWorkflowId],
      file_list: this.selectorWorkflowId
    }).then((res: any) => {
      console.log(res)
      if (res && res.error_code == "AIS.0000") {
        this.JobTestId = res.result.job_id

        this.getTestModelWorkflowJob();
        this.message.success("文件测试成功，正在获取测试结果，请稍后！");
      } else if (res && res.error_code != "AIS.0000") {
        this.message.error("文件测试失败，请重试");
      }
    }).catch((err: any) => {
      this.message.error(err.error_msg);
    })
  }

  getTestModelWorkflowJob() {
    let that = this;
    that.workflowJobTimer = setInterval(function () {
      that.http.post('/contract-extraction/job-mgr/query-job', {
        job_id: that.JobTestId
      }).then((res: any) => {
        if (res.result) {
          if (res.result.job_status == "success") {
            that.conifgJobcontent = res.result.job_result.content
            that.exportFileBase64 = res.result.job_result.export_file_base64
            that.exportFileName = res.result.job_result.export_filename;
            that.message.success("成功获取测试结果！");
            if (that.workflowJobTimer != null) {
              clearInterval(that.workflowJobTimer)
            }
          } else if (res.result.job_status == "waiting") {
            that.message.info(that.JobTestId + "正在排队等待，请稍后！");
          } else if (res.result.job_status == "running") {
            that.message.info(that.JobTestId + "正在查询，请稍后！");
          } else {
            that.message.error(that.JobTestId + "查询失败，请重试！");
            if (that.workflowJobTimer != null) {
              clearInterval(that.workflowJobTimer)
            }
          }
        }
        else {
          that.message.error(that.JobTestId + "轮询查询失败，请重试！");
          if (that.workflowJobTimer != null) {
            clearInterval(that.workflowJobTimer)
          }
        }
      }).catch((data: any) => {
        that.message.error(that.JobTestId + data.error_msg);
        if (that.workflowJobTimer != null) {
          clearInterval(that.workflowJobTimer)
        }
      })
    }, 3000);
  }
  // 点击显示测试结果文本
  ShowDataBox(data){
    this.ShowDataValue = true
    console.log(data)
    this.ShowDataName = data.file_name
    this.ShowDataExtract = data.extract_result
  }
  ModaltestData(data){
    this.ShowDataValue = true
    console.log(data)
    this.ShowDataName = data.file_name
    this.ShowDataExtract = data.extract_result
  }
  ModalWorkflowData(data){
    this.ShowDataValue = true
    console.log(data)
    this.ShowDataName = data.file_name
    this.ShowDataExtract = data.extract_result
  }
  ModalWorkflowShowData(data){
    this.ShowDataValue = true
    console.log(data)
    this.ShowDataName = data.file_name
    this.ShowDataExtract = data.extract_result
  }
}

